#!/usr/bin/env pwsh
<#
.SYNOPSIS
    简化的API测试脚本 - 适用于服务器未运行的情况
.DESCRIPTION
    提供基本的API测试和模拟调用，用于验证API设计和问题诊断
#>

# 配置
$BaseURL = "http://localhost:8000/api/v1/enhanced-training"

function Test-APIDesign {
    Write-Host "🔍 分析增强训练API设计" -ForegroundColor Cyan
    Write-Host "=" * 60
    
    Write-Host "📋 API端点列表:" -ForegroundColor Yellow
    Write-Host "  POST   $BaseURL/train/start          - 启动训练"
    Write-Host "  GET    $BaseURL/train/status         - 获取训练状态"
    Write-Host "  GET    $BaseURL/train/results        - 获取训练结果"
    Write-Host "  GET    $BaseURL/train/interpretability/{model} - 获取可解释性分析"
    Write-Host "  POST   $BaseURL/train/stop           - 停止训练"
    Write-Host "  GET    $BaseURL/models/status        - 获取模型状态"
    
    Write-Host "`n📝 标准训练配置:" -ForegroundColor Yellow
    $config = @{
        train_range = "3_months"
        enable_parallel = $true
        enable_shap = $true
        dynamic_weights = $true
        models = @("lightgbm", "xgboost", "ensemble")
        lightgbm = @{
            learning_rate = 0.05
            num_leaves = 31
            feature_fraction = 0.9
            bagging_fraction = 0.8
            lambda_l1 = 0.1
            lambda_l2 = 0.1
        }
        xgboost = @{
            learning_rate = 0.05
            max_depth = 4
            n_estimators = 100
            subsample = 0.6
            colsample_bytree = 0.6
            reg_alpha = 0.5
            reg_lambda = 0.5
        }
    }
    
    $jsonConfig = $config | ConvertTo-Json -Depth 10
    Write-Host $jsonConfig -ForegroundColor Gray
}

function Test-CodeIssues {
    Write-Host "`n🐛 代码问题分析" -ForegroundColor Red
    Write-Host "=" * 60
    
    Write-Host "⚠️  已识别的潜在问题:" -ForegroundColor Yellow
    
    Write-Host "`n1. 依赖问题:" -ForegroundColor Cyan
    Write-Host "   - SHAP库可能未安装 (line 27-32 in enhanced_dual_trainer.py)"
    Write-Host "   - MultiOutputRegressor可能导致内存问题"
    Write-Host "   - 数据库连接可能失败"
    
    Write-Host "`n2. 数据加载问题:" -ForegroundColor Cyan
    Write-Host "   - load_data()函数可能因数据不足失败 (line 141-195)"
    Write-Host "   - 历史数据缺失时用固定值填充可能影响训练质量"
    Write-Host "   - 气象数据缺失时默认值可能不合理"
    
    Write-Host "`n3. 训练配置问题:" -ForegroundColor Cyan
    Write-Host "   - XGBoost参数过度保守可能影响性能 (max_depth=4, n_estimators=100)"
    Write-Host "   - 特征选择可能过于激进 (保留600个特征)"
    Write-Host "   - 小样本下SHAP分析样本过少 (sample_size=10)"
    
    Write-Host "`n4. 并发问题:" -ForegroundColor Cyan
    Write-Host "   - 线程池可能因资源限制失败"
    Write-Host "   - 全局训练状态管理可能存在竞态条件"
    Write-Host "   - 数据库并发写入可能失败"
    
    Write-Host "`n5. 错误处理问题:" -ForegroundColor Cyan
    Write-Host "   - 训练失败时状态清理不完整"
    Write-Host "   - 异常时模型文件可能损坏"
    Write-Host "   - 数据库事务可能未正确回滚"
}

function Test-RecommendedFixes {
    Write-Host "`n🔧 建议修复方案" -ForegroundColor Green
    Write-Host "=" * 60
    
    Write-Host "1. 环境配置修复:" -ForegroundColor Yellow
    Write-Host "   pip install shap scikit-learn lightgbm xgboost fastapi uvicorn sqlalchemy"
    Write-Host "   conda create -n lfforecast python=3.8"
    Write-Host "   conda activate lfforecast"
    
    Write-Host "`n2. 数据问题修复:" -ForegroundColor Yellow
    Write-Host "   - 检查数据库连接和数据完整性"
    Write-Host "   - 增加数据验证和清理逻辑"
    Write-Host "   - 优化数据填充策略"
    
    Write-Host "`n3. 模型参数优化:" -ForegroundColor Yellow
    Write-Host "   - 调整XGBoost参数适应数据规模"
    Write-Host "   - 优化特征选择策略"
    Write-Host "   - 增加交叉验证"
    
    Write-Host "`n4. 错误处理增强:" -ForegroundColor Yellow
    Write-Host "   - 添加更详细的日志记录"
    Write-Host "   - 改进异常处理和状态恢复"
    Write-Host "   - 增加训练中断和恢复机制"
}

function Generate-TestCommands {
    Write-Host "`n🚀 PowerShell测试命令" -ForegroundColor Magenta
    Write-Host "=" * 60
    
    Write-Host "完整测试:" -ForegroundColor Yellow
    Write-Host "  ./test_enhanced_training_api.ps1"
    Write-Host "  ./test_enhanced_training_api.ps1 -Action complete -TrainRange 1_month"
    
    Write-Host "`n分步测试:" -ForegroundColor Yellow
    Write-Host "  ./test_enhanced_training_api.ps1 -Action connection"
    Write-Host "  ./test_enhanced_training_api.ps1 -Action status"
    Write-Host "  ./test_enhanced_training_api.ps1 -Action start -TrainRange 1_month"
    Write-Host "  ./test_enhanced_training_api.ps1 -Action monitor"
    Write-Host "  ./test_enhanced_training_api.ps1 -Action results"
    
    Write-Host "`n压力测试:" -ForegroundColor Yellow
    Write-Host "  ./test_enhanced_training_api.ps1 -Action stress"
    Write-Host "  ./test_enhanced_training_api.ps1 -StressTest"
    
    Write-Host "`n手动API测试 (使用curl):" -ForegroundColor Yellow
    Write-Host '  curl -X GET "http://localhost:8000/api/v1/enhanced-training/models/status"'
    Write-Host '  curl -X POST "http://localhost:8000/api/v1/enhanced-training/train/start" \'
    Write-Host '       -H "Content-Type: application/json" \'
    Write-Host '       -d "{\"train_range\":\"1_month\",\"enable_parallel\":true}"'
}

function Generate-BugReport {
    Write-Host "`n📋 问题排查清单" -ForegroundColor Blue
    Write-Host "=" * 60
    
    Write-Host "环境检查:" -ForegroundColor Yellow
    Write-Host "  □ Python环境是否正确配置"
    Write-Host "  □ 所有依赖包是否已安装"
    Write-Host "  □ 数据库连接是否正常"
    Write-Host "  □ 端口8000是否被占用"
    
    Write-Host "`n数据检查:" -ForegroundColor Yellow
    Write-Host "  □ LoadData表是否有数据"
    Write-Host "  □ WeatherDaily表是否有数据"
    Write-Host "  □ 数据时间范围是否充足"
    Write-Host "  □ 数据质量是否良好"
    
    Write-Host "`n模型检查:" -ForegroundColor Yellow
    Write-Host "  □ 特征工程是否正确"
    Write-Host "  □ 模型参数是否合理"
    Write-Host "  □ 内存使用是否超限"
    Write-Host "  □ 计算资源是否充足"
    
    Write-Host "`n日志检查:" -ForegroundColor Yellow
    Write-Host "  □ FastAPI服务日志"
    Write-Host "  □ 训练器执行日志"
    Write-Host "  □ 数据库操作日志"
    Write-Host "  □ 系统资源使用日志"
}

# 主程序
Write-Host "🔧 增强训练API测试和问题诊断工具" -ForegroundColor Magenta
Write-Host "=" * 80

Test-APIDesign
Test-CodeIssues  
Test-RecommendedFixes
Generate-TestCommands
Generate-BugReport

Write-Host "`n✅ 分析完成！请按照建议进行问题排查和修复。" -ForegroundColor Green